package com.basker.pisces.springcloud.locale;

import java.util.Locale;

import org.springframework.context.i18n.LocaleContextHolder;

import com.basker.pisces.context.LoginContext;
import com.basker.pisces.context.LoginContextHolder;
import com.basker.pisces.service.constant.ServiceConstants;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * 用feign发起请求时，当前拦截器负责将上下文中的。
 *
 * <p>
 * 优先从LoginContext中获取，如果存在，则不再发生Locale的消息头
 *
 * @author hangwen
 */
public class ClientLocaleInterceptor implements RequestInterceptor {

    private static final String LOCAL_PARAM_NAME = ServiceConstants.MessageHead.LOCAL_KEY;

    @Override
    public void apply(RequestTemplate template) {
        Locale locale = this.tryGetLocaleFromLoginContext();
        if (locale == null) {
            locale = LocaleContextHolder.getLocale();
        }

        if (locale != null) {
            template.header(LOCAL_PARAM_NAME, locale.toString());
        }
    }

    private Locale tryGetLocaleFromLoginContext() {
        LoginContext loginContext = LoginContextHolder.getLoginContext();
        if (loginContext == null) {
            return null;
        }

        return loginContext.getLocaleObject();
    }

}
